package com.xl.rentkeeper.net;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;

import com.xl.rentkeeper.App;
import com.xl.rentkeeper.business.MsgLogic;
import com.xl.rentkeeper.business.UserLogic;
import com.xl.rentkeeper.log.QLog;
import com.xl.rentkeeper.mgr.ThreadManager;
import com.xl.rentkeeper.msg.Message;


/**
 * 网络管理模块，负责网络状态监听，网络事件处理
 * 
 * @author
 *
 */
public class NetworkManager {

	public static final String tag = "NetworkManager";

    public static final int NET_NONE = 1;
    public static final int NET_2G = 2;
    public static final int NET_3G = 3;
    public static final int NET_4G = 4;
    public static final int NET_WIFI = 5;
	int mNetworkType = NET_NONE;
	private String mApnType = "";
	// 加一个timer避免
	private Handler mHandler;
	private Runnable checkRun = new Runnable() {
		@Override
		public void run() {
			onNetChange();
			mHandler.postDelayed(this, 2 * 60 * 1000);
		}
	};

	static NetworkManager sIns = null;
	public static String getNetStateTip(int state){
		switch (state){
			case NET_NONE:
				return "无网络连接";
			case NET_2G:
				return "2G网络";
			case NET_3G:
				return "3G网络";
			case NET_4G:
				return "4G网络";
			case NET_WIFI:
				return "WiFi网络";
			default:
				break;
		}
		return "无网络连接";
	}
	private NetworkManager() {
		mHandler = new Handler(Looper.getMainLooper());
		mHandler.postDelayed(checkRun, 1 * 60 * 1000);
		registerDateTransReceiver();
		updateNetInfo();
	}

	public static NetworkManager getInstance() {
		if (sIns == null) {
			synchronized (NetworkManager.class) {
				if (sIns == null) {
                    sIns = new NetworkManager();
				}
			}
		}
		return sIns;
	}


	public synchronized void updateNetInfo() {
		try {
			int oldType = mNetworkType;
			int netType = NetworkUtil.getSystemNetwork(App.getApp());
			mNetworkType = netType;
			QLog.d(tag, "oldType=" + Integer.toString(oldType)
					+ "; netType=" + Integer.toString(netType));
			if (netType != oldType) {
				notifyNetChange(oldType,netType);
			}
			ConnectivityManager connectivityManager = (ConnectivityManager) App
					.getApp().getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo activeNetworkInfo = connectivityManager
					.getActiveNetworkInfo();
			String exrea = null;
			if (activeNetworkInfo != null) {
				exrea = activeNetworkInfo.getExtraInfo();
			}
            QLog.d(tag, "net event:" + mNetworkType + " " + exrea);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public synchronized void onNetChange() {
		updateNetInfo();
	}

	public int getNetType() {
		return mNetworkType;
	}

	public synchronized String getApnType() {
		return mApnType;
	}

	public static final String CONNECTIVITY_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";

	private void registerDateTransReceiver() {
		IntentFilter filter = new IntentFilter();
		filter.addAction(CONNECTIVITY_CHANGE_ACTION);
		App.getApp().registerReceiver(new NetStatReceiver(), filter);
	}

	public class NetStatReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
            QLog.d(tag,"action:"+action);
			if (TextUtils.equals(action, CONNECTIVITY_CHANGE_ACTION)) {// 网络变化的时候会发送通知
				updateNetInfo();
				return;
			}
		}
	}

	void notifyNetChange(int oldType,int newType) {
		if (oldType == NET_NONE) {
			// 看是否有需要建立连接
			ThreadManager.getInstance().runOnWorkerThread(new Runnable() {
				@Override
				public void run() {
					NetEngine.getInstance().trySendingOne();
				}
			},0);
		}
		if(UserLogic.getInstance().isLogin()){
			String tips = NetworkManager.getNetStateTip(newType);
			Message msg = new Message();
			long time = System.currentTimeMillis();
			msg.msgTime = time;
			msg.receivingTime =time;
			msg.seq = time;
			msg.netState = tips;
			QLog.d(tag, "onReceive:" + tips);
			MsgLogic.getInstance().onNetStateChange(msg);
			MsgLogic.getInstance().pullMsg();
		}
    }
}
